package com.wwlwxg.filemanager.util;

import com.zhazhapan.util.Checker;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: coco
 * @time 2019/2/11 - 11:04
 */
public class ControllerUtils {

    private ControllerUtils() {}

    ControllerUtils instance = new ControllerUtils();

    public ControllerUtils getInstance() {
        return instance;
    }

    /**
     * 加载本地资源
     */
    public static void loadResource(HttpServletResponse response, String path, boolean download) throws IOException {
        if(Checker.isNotEmpty(path)) {
            File file = new File(path);
            if(download) {
                setResponseFileName(response, file.getName());
            }
            FileInputStream in = new FileInputStream(file);
            ServletOutputStream os = response.getOutputStream();
            byte[] b;
            while(in.available() > 0) {
                b = in.available() > 1024 ? new byte[1024] : new byte[in.available()];
                in.read(b, 0, b.length);
                os.write(b, 0, b.length);
            }
            in.close();
            os.flush();
            os.close();
        }
    }

    public static void setResponseFileName(HttpServletResponse response,  String fileName) throws UnsupportedEncodingException {
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),
                "ISO-8859-1"));
    }
}
